package java;

import java.util.function.Consumer;

public class ABC轮流打印线程 implements Runnable {
    private Object after;
    private Object self;
    private Consumer consumer;
    private String str;

    public ABC轮流打印线程(Object after, Object self, String str, Consumer consumer) {
        this.after = after;
        this.self = self;
        this.str = str;
        this.consumer = consumer;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (true) {
            synchronized (after) {
                synchronized (self) {
                    consumer.accept(str);
                    self.notify();
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    after.wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
